package util

import (
	"bytes"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"
)

func init() {
	orm.RegisterDriver("mysql", orm.DRMySQL)
	var dbstr bytes.Buffer
	dbstr.WriteString(beego.AppConfig.String("mysqluser"))
	dbstr.WriteString(":")
	dbstr.WriteString(beego.AppConfig.String("mysqlpass"))
	dbstr.WriteString("@tcp(")
	dbstr.WriteString(beego.AppConfig.String("mysqlurls"))
	dbstr.WriteString(")/")
	dbstr.WriteString(beego.AppConfig.String("mysqldb"))
	dbstr.WriteString("?charset=utf8")
	maxIdleConns, _ := beego.AppConfig.Int("maxIdleConns")
	maxOpenConns, _ := beego.AppConfig.Int("maxOpenConns")
	orm.RegisterDataBase("default", "mysql", dbstr.String(), maxIdleConns, maxOpenConns)
}

func Insert(obj interface{}) (interface{}, error) {
	o := orm.NewOrm()
	res, err := o.Insert(obj)
	if err == nil {
		return res, nil
	}
	return nil, err
}

func Update(obj interface{}, args []string) (interface{}, error) {
	o := orm.NewOrm()
	res, err := o.Update(obj, args...)
	if err == nil {
		return res, nil
	}
	return nil, err
}

func Delete(obj interface{}) (interface{}, error) {
	o := orm.NewOrm()
	res, err := o.Delete(obj)
	if err == nil {
		return res, nil
	}
	return nil, err
}
